﻿using GameData.Domains.Mod;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TaiwuModFramework.Common.Abstract;
using TaiwuModFramework.Common.Base;
using TaiwuModFramework.Common.Info;
using TaiwuModFramework.Frontend.ConfigItemReader;

namespace TaiwuModFramework.Frontend {
    public class FwDomain : AFwDomain {

        

        public static  ModInfo ModInfo { get; internal set; }

        private FwDomain() {
        }


        internal static void Init(string idStr) {
            if(ModIdStr != null) return;    // 已经初始化过了
            ModIdStr = idStr;
            ModInfo = GetModInfo(idStr);
            // 配置日志工具
            UseLog(new BaseLogger("FwFrontend", ALogger.LEVEL.INFO, BaseLogWriter.GetLogWriter("./Mod/TaiwuModFramework/Logs/Frontend.log")));
            // 配置获取配置项值的委托
            RegConfigItemReader(new IntReader(), new BoolReader(), new FloatReader(), new StringReader());
            MsgClient = new BaseMsgClient(ShareMemoryDefaultPath, true);
            ReqClient = new BaseReqClient();

        }


        /// <summary>
        /// 获取mod信息
        /// </summary>
        /// <param name="modIdStr"></param>
        /// <returns></returns>
        public static ModInfo GetModInfo(string modIdStr) {
            Dictionary<string, ModInfo> dict = (Dictionary<string, ModInfo>)(typeof(ModManager).GetField("_localMods", (BindingFlags)(-1)).GetValue(null));
            dict.TryGetValue(modIdStr, out ModInfo modInfo);
            return modInfo;
        }



        public static void UpdateBackendConfigItem(string modIdStr, Type type, string configName, object value) {
            string key = ConfigItemInfo.CalcKey(type, configName);
            // 发送请求更新
            ReqClient.Req(modIdStr, "UpdateConfigItem")
                .SetArgTypes(typeof(string), typeof(string), typeof(object))
                .SetArgs(modIdStr, key, value).SendNotify();  // 发送通知，即不会有返回值
        }

        public static List<string> GetAllConfigItemKey(string modIdStr) {
            return (List<string>)ReqClient.Req(ModIdStr, "PrintAllItem")
                .SetArgTypes(typeof(string))
                .SetArgs(ModIdStr)
                .SendReq(out RespInfo resp);    // 发送同步请求,该服务方法在后端日志中输出配置项，并以列表形式返回给前端
        }
    }
}
